#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <memory>
#include <cstring>
#include <unistd.h>

static void usage(std::string process)
{
    std::cout << "Invalid command line arguments. Usage: " << process << "-> ip | port" << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 3){
        usage(argv[0]);
        exit(1);
    }

    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);
    bool alive = false; // 表示客户端与 服务器的连接状态
    int sock = 0;
    // 循环 进行连接
    while(true)
    {
        if(!alive) // 未建立连接时，执行下面代码
        {
            sock = socket(AF_INET, SOCK_STREAM, 0);
            if(sock < 0) // 创建失败
            {
                std::cerr << "socket erorr" << std::endl;
                exit(2);
            }
            // 创建+初始化 sockaddr_in 对象
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(serverport);
            server.sin_addr.s_addr = inet_addr(serverip.c_str());

            if(connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0)
            {
                std::cerr << "connect error" << std::endl;
                exit(3);
            }
            std::cout << "connect success" << std::endl;
            alive = true;
        }
        std::cout << "输入信息# ";
        std::string line;
        std::getline(std::cin, line);
        if(line == "quit")
            break;

        ssize_t s = send(sock, line.c_str(), line.size(), 0);
        if(s > 0) // 发送成功
        {
            char buffer[1024];
            s = recv()
        }
        else // 发送失败
        {
            alive = false;
            close(sock);
        }
    }

}